import { syncJiaXiao } from '@/api/campus/campus'
import { getDictionaryDataSelector } from '@/api/systemData/dictionary'
import request from '@/utils/request'

import RecordsHandleForm from '../insurance/Records/index.vue'
import StatusBox from '../renewal/StatusBox'
import CloseSupportForm from '../supportClose/Form/index.vue'
import ExportBox from './ExportBox'
import CustomForm from './Form'
import RecordsForm from './Records/index.vue'

export default {
  name: 'campus',
  components: { CustomForm, ExportBox, StatusBox, RecordsForm, RecordsHandleForm, CloseSupportForm },
  data() {
    return {
      showAll: false,
      query: {
        brand: 'bell',
        enCode: undefined,
        area: undefined,
        type: undefined,
        stateMark: undefined,
        openDate: undefined,
        businessName: undefined,
        contact: undefined,
        endDate: undefined,
        inurance: undefined,
        inuranceDate: [],
        openTags: undefined,
        notOpenTags: undefined,
        birthday: undefined,
        company: undefined
      },
      list: [],
      listLoading: true,
      multipleSelection: [],
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'createTime'
      },
      formVisible: false,
      exportBoxVisible: false,
      statusVisible: false,
      closeSupportVisible: false,
      recordsVisible: false,
      recordsHandleVisible: false,
      columnList: [{ prop: 'brand', label: '校区品牌' }, { prop: 'code', label: '校区编码' }, { prop: 'fullName', label: '校区全称' }, { prop: 'investors', label: '投资人' }, { prop: 'shortName', label: '校区简称' }, { prop: 'telephone', label: '固定电话' }, { prop: 'email', label: '校区邮箱' }, { prop: 'manager', label: '负责人' }, { prop: 'managerMobile', label: '电话' }, { prop: 'wechat', label: '微信' }, { prop: 'provinceId', label: '省份' }, { prop: 'cityId', label: '城市' }, { prop: 'type', label: '校区类型' }, { prop: 'status', label: '校区状态' }, { prop: 'openDate', label: '开业日期' }, { prop: 'startDate', label: '服务开始日期' }, { prop: 'endDate', label: '服务截止日期' }, { prop: 'insurance', label: '保险备注' }, { prop: 'insuranceNo', label: '保险单号' }, { prop: 'insuranceDate', label: '保险到期日' }, { prop: 'businessName', label: '营业执照主体' }, { prop: 'businessNo', label: '营业执照号' }],
      typeOptions: [],
      statusOptions: [],
      brandOptions: [],
      levelOptions: [],
      companyOptions: [],
      inuranceOptions: [
        {
          enCode: '1',
          fullName: '未参保'
        },
        {
          enCode: '2',
          fullName: '已参保'
        },
        {
          enCode: '3',
          fullName: '已过期'
        }
      ],
      tagsOptions: [
        {
          enCode: 'website',
          fullName: '官网'
        },
        {
          enCode: 'tiktok',
          fullName: '抖音'
        }
      ]
    }
  },
  computed: {},
  created() {
    this.initData()
    this.gettypeOptions()
    this.getstateMarkOptions()
    this.getBrandOptions()
    this.getLevelOptions()
    this.getCompanyOptions()
  },
  methods: {
    handleAttributeTags(row, value) {
      console.log(row)
      this.$confirm('确定' + (row.attributeTags && row.attributeTags.indexOf(value) > -1 ? '取消' : '点亮') + '该图标, 是否继续?', '提示', {
        type: 'warning'
      })
        .then(() => {
          request({
            url: `/api/campus/${row.id}/setAttributeTags/${value}`,
            method: 'PUT'
          }).then(res => {
            this.$message({
              type: 'success',
              message: res.msg,
              onClose: () => {
                this.initData()
              }
            })
          })
        })
        .catch(() => {})
    },
    /**
     * 导出校区信息
     * 功能：统一调用后端导出接口，按 `type` 分支生成两版 Excel。
     * - 招商版（type!='kefu'）：品牌、校区名称、校区地址、投资人姓名、服务起止日期、运营状态、运营阶段、学生数、老师数、班级数。
     * - 客服增强版（type=='kefu'）：在招商版基础上，增加校区编码、校区对接人、对接人电话、保单号、保险名称、保险到期日、双师账号、账号到期日。
     * 请求：GET `api/campus/export-campus-info?type=${tp}`
     * 交互：点击按钮触发，成功后若返回 `url` 则新窗口打开下载地址；否则提示站内信查收。
     * @param {string} tp - 导出类型，'zhaoshang' 或 'kefu'
     */
    exportCampusInfo(tp) {
      // 可根据需要将筛选条件一并传递到后端（当前接口不强制要求）
      request({
        url: `/api/campus/export-campus-info?type=${tp}`,
        method: 'GET',
        data: {}
      }).then(res => {
        // 兼容旧版构建环境的写法，避免使用可选链操作符
        const url = res && res.data && res.data.url
        if (url) {
          // 后端返回相对路径时，拼接为完整下载地址
          window.open(this.define.comUrl + url)
        } else {
          // 若未返回直接下载链接，提示用户前往站内信获取
          this.$message({
            message: '文件下载链接稍后推送到站内信，请在右上角铃铛图标处查收！',
            type: 'success',
            showClose: true,
            duration: 0
          })
        }
      })
    },

    /**
     * 家校平台同步按钮点击处理函数
     * 功能：弹窗确认后调用后端 API，同步校区信息到家校平台
     * 请求：POST `api/campus/async/jiaxiao/{id}/{type}`
     * 参数：
     * - id: 校区主键ID字符串
     * - type: 同步类型（'create' | 'sync' | 'changeAdmin'）
     * 成功：弹出成功消息（后端返回的 msg）
     * 失败：由 axios 响应拦截器统一处理并提示
     */
    handleAsyncJiaXiao(id, type) {
      console.log(id, type)
      this.$confirm(`您现在同步数据到家校平台, 是否继续?`, '提示', {
        type: 'warning'
      })
        .then(() => {
          syncJiaXiao({ id, type }).then(res => {
            this.$message({
              type: 'success',
              message: res.msg,
              duration: 1000
            })
          })
        })
        .catch(() => {})
    },
    recordsHandle(id) {
      this.recordsHandleVisible = true
      this.$nextTick(() => {
        this.$refs.RecordsHandleForm.init(id)
      })
    },
    onRecordsFormHandle(id) {
      this.recordsVisible = true
      this.$nextTick(() => {
        this.$refs.RecordsForm.init(id)
      })
    },
    getBrandOptions() {
      this.$store.dispatch('base/getDictionaryData', { sort: 'Brand' }).then(res => {
        this.brandOptions = res
      })
    },
    getLevelOptions() {
      getDictionaryDataSelector('CampusLevel').then(res => {
        this.levelOptions = res.data.list
      })
    },
    gettypeOptions() {
      getDictionaryDataSelector('CampusType').then(res => {
        this.typeOptions = res.data.list
      })
    },
    getstateMarkOptions() {
      getDictionaryDataSelector('CampusStatus').then(res => {
        this.statusOptions = res.data.list
      })
    },
    getCompanyOptions() {
      getDictionaryDataSelector('MANAGEMENT_AREA')
        .then(res => {
          this.companyOptions = res.data.list.map(item => ({
            enCode: item.enCode,
            label: item.fullName
          }))
        })
        .catch(error => {
          console.error('获取管理区域数据字典失败:', error)
        })
    },
    initData() {
      this.listLoading = true
      let _query = {
        ...this.listQuery,
        ...this.query
      }
      let query = {}
      for (let key in _query) {
        if (Array.isArray(_query[key])) {
          query[key] = _query[key].join()
        } else {
          query[key] = _query[key]
        }
      }
      request({
        url: `api/campus`,
        method: 'GET',
        data: query
      }).then(res => {
        this.list = res.data.list
        this.total = res.data.pagination.total
        this.listLoading = false
      })
    },
    templateDownload(name) {
      request({
        url: `/api/campus/Actions/ExportBirthday`,
        method: 'GET',
        data: this.query
      }).then(res => {
        this.$message({
          message: '文件下载链接稍后推送到站内信，请在右上角铃铛图标处查收！',
          type: 'success',
          showClose: true,
          duration: 0
        })
      })
    },

    onSortChange(column) {
      if (column.order == 'ascending') {
        this.listQuery.sidx = column.prop
        this.listQuery.sort = 'asc'
      } else if (column.order == 'descending') {
        this.listQuery.sidx = column.prop
        this.listQuery.sort = 'desc'
      } else {
        this.listQuery.sidx = 'createTime'
        this.listQuery.sort = 'desc'
      }
      this.initData()
    },
    changeStatusHandle(campusId, status) {
      this.statusVisible = true
      this.$nextTick(() => {
        this.$refs.StatusBox.init(campusId, status)
      })
    },
    changeCloseHandle(row, status) {
      this.closeSupportVisible = true
      this.$nextTick(() => {
        this.$refs.CloseSupport.init(row, '', status)
      })
    },
    changeTransferHandle(campusId, level) {
      this.$nextTick(() => {
        this.$confirm(`您确定要${level == 'supervision_S3' ? '移交' : '退回'}该操作, 是否继续?`, '提示', {
          type: 'warning'
        })
          .then(() => {
            this.listLoading = true
            request({
              url: `api/campus/transfer/${level}`,
              method: 'POST',
              data: { ids: campusId }
            }).then(res => {
              this.$message({
                type: 'success',
                message: res.msg,
                onClose: () => {
                  this.listLoading = false
                }
              })
            })
          })
          .catch(() => {
            this.listLoading = false
          })
      })
    },
    formattedInfo(info) {
      if (info != '') {
        const people = info.split('/')
        return people
          .map(person => {
            const [name, phone] = person.split('(')
            if (phone != undefined && phone.length > 7) {
              const prefix = phone.slice(0, 3)
              const suffix = phone.slice(7)
              return `${name}(${prefix}****${suffix}`
            } else {
              return people
            }
          })
          .join('/')
      }
    },
    handleDel(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        type: 'warning'
      })
        .then(() => {
          request({
            url: `api/campus/${id}`,
            method: 'DELETE'
          }).then(res => {
            this.$message({
              type: 'success',
              message: res.msg,
              onClose: () => {
                this.initData()
              }
            })
          })
        })
        .catch(() => {})
    },
    addOrUpdateHandle(id, isDetail) {
      this.formVisible = true
      this.$nextTick(() => {
        this.$refs.CustomForm.init(id, isDetail)
      })
    },
    exportData() {
      this.exportBoxVisible = true
      this.$nextTick(() => {
        this.$refs.ExportBox.init(this.columnList)
      })
    },
    download(data) {
      let _query = {
        ...this.listQuery,
        ...this.query
      }
      let query1 = {}
      for (let key in _query) {
        if (Array.isArray(_query[key])) {
          query1[key] = _query[key].join()
        } else {
          query1[key] = _query[key]
        }
      }
      let query = { ...data, ...query1 }
      request({
        url: `api/campus/Actions/Export`,
        method: 'GET',
        data: query
      }).then(res => {
        if (!res.data.url) return
        window.open(this.define.comUrl + res.data.url)
        this.$refs.ExportBox.visible = false
        this.exportBoxVisible = false
      })
    },
    search() {
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'createTime'
      }
      this.initData()
    },
    refresh(isrRefresh) {
      this.formVisible = false
      if (this.recordsVisible) {
        this.recordsVisible = false
      }
      if (this.recordsHandleVisible) {
        this.recordsHandleVisible = false
      }
      if (this.closeSupportVisible) {
        this.closeSupportVisible = false
      }
      if (isrRefresh) this.reset()
    },
    reset() {
      for (let key in this.query) {
        this.query[key] = undefined
      }
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: 'desc',
        sidx: 'createTime'
      }
      this.initData()
    }
  }
}
